/*
 * TsApplication.cpp
 *
 *  Created on: 2016年4月6日
 *      Author: terry
 */

#include "TsApplication.h"
#include "Socket.h"
#include "CLog.h"
#include "Ffmpeg.h"
#include "TcpServer.h"


typedef comn::Singleton< TsApplication >		TsApplicationSingleton;


int getCLogLevel(int level)
{
	if (level <= AV_LOG_FATAL)
	{
		return CLog::kFatal;
	}
	else if (level <= AV_LOG_ERROR)
	{
		return CLog::kError;
	}
	else if (level <= AV_LOG_WARNING)
	{
		return CLog::kWarning;
	}
	else if (level <= AV_LOG_INFO)
	{
		return CLog::kInfo;
	}
	else
	{
		return CLog::kDebug;
	}
}

void av_log_callback(void *avcl, int level, const char *fmt, va_list vl)
{
	//av_log_default_callback(avcl, level, fmt, vl);

	if (level <= AV_LOG_WARNING)
	{
		CLog::logv(getCLogLevel(level), fmt, vl);
	}
}

TsApplication& TsApplication::instance()
{
	return TsApplicationSingleton::instance();
}

TsApplication::TsApplication()
{
}

TsApplication::~TsApplication()
{
}


int TsApplication::init()
{
	if (0 != CLog::startup("TsCasterLog.ini"))
	{
		CLog::setLogger(CLog::DEBUGWINDOW);
	}

	comn::Socket::startup();

	av_register_all();
	avformat_network_init();

	av_log_set_level(AV_LOG_WARNING);
	av_log_set_callback(av_log_callback);
	
    TcpServer::Startup();

	return 0;
}

void TsApplication::quit()
{
	m_casters.clear();

    TcpServer::Cleanup();

	comn::Socket::cleanup();
}


int TsApplication::put(TsMediaCasterPtr& caster)
{
	if (!caster)
	{
		return -1;
	}

	return m_casters.put(caster);
}

TsMediaCasterPtr TsApplication::get(int idx)
{
    if (idx < 0 || idx >= (int)m_casters.max_size())
    {
        return TsMediaCasterPtr();
    }
	return m_casters.getAt(idx);
}

TsMediaCasterPtr TsApplication::remove(int idx)
{
	TsMediaCasterPtr caster;
	m_casters.remove(idx, caster);
	return caster;
}

